'use strict';

var crypto = require('crypto');
function md5(text) {
    return crypto.createHash('md5').update(text, "utf8").digest('hex');
};

var fs = require("fs");
var getFilesMd5s = function (root) {
    console.log("this dir is : " + root);
    if (!fs.existsSync(root)) {
        console.log("this dir is not exist!" + root);
        return;
    }
    var arrayex = ['.js', '.json', '.html', '.css', '.png', 'jpg', 'gif'];
    var array = [];

    var getFiles = function (dirPath) {
        let files = fs.readdirSync(dirPath, "utf8");
        for (let i in files) {
            let path = dirPath + "/" + files[i];
            // console.log(path);
            let stats = fs.statSync(path);
            if (stats.isFile()) {
                let ex = path.substring(path.lastIndexOf('.'));
                let index = arrayex.indexOf(ex);
                if (index < 0) continue;              
                array.push(path);
            } else if (stats.isDirectory()) {
                getFiles(path);
            } else {
            }
        }
    }


    getFiles(root);

    var res = {};
    var arrayexfile = ['index.html','js/_common/baseConfig.js', 'js/system/replacement.js'];
    for (let i in array) {
        let content = fs.readFileSync(array[i], "utf8");
        array[i] = array[i].replace(root + "/", "");
        let index = arrayexfile.indexOf(array[i]);
        if (index >= 0) continue;
        console.log((Number(i * 100 / array.length).toFixed(1)) + "%\t" + array[i]);
        res[array[i]] = md5(content).toLowerCase().substring(8, 24);
    }

    var outRes = root + "/js/system/replacement.js";
    console.log("正在写入中....." + outRes);
    fs.writeFileSync(outRes, "define(" + JSON.stringify(res) + ");");
    console.log("end...............");
    // fs.close();
}

var args = process.argv.splice(2);
console.log('所传递的参数是：', args);

var root = args[0] || args[1] || "D:\\Work\\mfxy\\client\\tw\\magica" || "E:/Git/HelloHtml/HBuilderProjects/HelloHBuilder";
//root = "E:\\Git\\HelloHtml\\HBuilderProjects\\HelloHBuilder\\js\\system\\replacement"
getFilesMd5s(root.replace(new RegExp("\\\\", "g"), "/"));